//
//  ReplayKit+Broadcast.swift
//  SwiftCode
//
//  Created by yuhus on 2023/9/21.
//  直播

import Foundation
import ReplayKit

extension ReplayKitExample: RPBroadcastActivityViewControllerDelegate {
  @objc func broadcastButtonTapped() {
    if isActive == false {
      presentBroadcastPicker()
    } else {
      stopBroadcast()
    }
  }
  
  private func presentBroadcastPicker() {
    // Set the origin point for the broadcast picker.
//    let broadcastPickerOriginPoint = CGPoint.zero
    
    RPBroadcastActivityViewController.load { broadcastActivtyViewController, error in
      if let error {
        Timber.d(error)
        return
      }
      
      broadcastActivtyViewController?.delegate = self
    }
    // Show the broadcast picker.
//    RPBroadcastActivityController.showBroadcastPicker(at: broadcastPickerOriginPoint,
//                                                      from: NSApplication.shared.mainWindow,
//                                                      preferredExtensionIdentifier: nil) { broadcastActivtyController, error in
//      if error == nil {
//        // There isn't an error presenting the broadcast picker.
//        // Save the broadcast activity controller reference.
//        self.activityController = broadcastActivtyController
//
//        // Set the broadcast activity controller delegate so that you
//        // can get the RPBroadcastController when the user finishes with the picker.
//        self.activityController.delegate = self
//      } else {
//        // There's an error when attempting to present the broadcast picker, so print the error.
//        print("Error attempting to present broadcast activity controller")
//      }
//    }
  }
  
  
  func stopBroadcast() {
    broadcastController.finishBroadcast { error in
      // Update the broadcast state.
      self.setBroadcastState(active: false)
      
      // Tear down the camera view.
//      self.tearDownCameraView()
      
      // Check and print the error, if necessary.
      if error != nil {
        print("Error attempting to stop in app broadcast")
      }
    }
  }
  
  func setBroadcastState(active: Bool) {
    DispatchQueue.main.async {
      if active == true {
        // Set the button title.
        self.broadcastButton.setTitle("Stop Broadcast", for: .normal)
      } else {
        // Set the button title.
        self.broadcastButton.setTitle("Start Broadcast", for: .normal)
      }
      
      // Set the internal recording state.
      self.isActive = active
      
      // Set the other buttons' isEnabled properties.
      self.recordButton.isEnabled = !active
      self.captureButton.isEnabled = !active
      self.clipButton.isEnabled = !active
    }
  }
  
  func broadcastActivityViewController(
    _ broadcastActivityViewController: RPBroadcastActivityViewController,
    didFinishWith broadcastController: RPBroadcastController?,
    error: Error?) {
      Timber.d(#function)
    }
}
